import React, {useEffect, useState} from 'react'
import {Form, Button, DatePicker, Input, Modal, Row, Col, message, Upload} from 'antd'
import {UploadOutlined} from '@ant-design/icons';
import moment from 'moment'
import {connect} from 'umi'
import {getUploadUrl} from "@/utils/upload";
import SelectUserModal from "@/pages/components/SelectUserModal";
import { SearchOutlined } from '@ant-design/icons';

const FormItem = Form.Item;
const {TextArea} = Input;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const {visible, onSubmit, onCancel, current, currentUser = {}, global = {}} = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [info, setInfo] = useState({});
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if (visible){
      if (current){
        setInfo({name: current.name,oid:current.oid,applyOid:current.oid});
        if (current.annexUrl){
          let fileUrlList = current.annexUrl.split(',');
          setFileUploadUrls(fileUrlList);
          fileUrlList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          })
        }
        current.jobLevel = jobLevel.find(item => (item.id === current.jobLevelId))?.name;
        current.applyTime = current.applyTime && moment(current.applyTime);
        form.setFieldsValue(current);
      }else {
        let data = {};
        data.applyOid = currentUser.id;
        data.applyName = currentUser.name;
        data.applyDepId = currentUser.depId;
        data.applyDepartment = currentUser.department;
        data.applyTime = moment();
        setInfo(data);
        form.setFieldsValue(data);
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    setFileUploadUrls([]);
    setInfo(null);
    uploadedFiles = [];
    form.resetFields();
    onCancel();
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    let id = current ? current.id : null;
    onSubmit({...fieldsValue, ...info, urlIdsList: fileUploadUrls, id});
    setInfo(null);
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const showSelectUserModal = () =>{
    setUserModalVisible(true);
  };

  const confirmSelectUser = (usersInfo) =>{
    if (usersInfo){
      let needsUserInfo = {
        oid: usersInfo[0].oid,
        code: usersInfo[0].code,
        name: usersInfo[0].name,
        hiredate: usersInfo[0].hiredate,
        workingYears: usersInfo[0].hiredate ? moment(usersInfo[0].hiredate).fromNow(true) : null,
        unitname: usersInfo[0].unitname,
        unitId: usersInfo[0].unitId,
        orgname: usersInfo[0].orgname,
        orgId: usersInfo[0].orgId,
        jobname: usersInfo[0].jobname,
        jobId: usersInfo[0].jobId,
        jobLevelType: usersInfo[0].jobLevelType,
        jobLevelId: usersInfo[0].jobLevelId,
        jobLevel: jobLevel.find(item => (item.id===usersInfo[0].jobLevelId))?.name,
        line: usersInfo[0].line,
        lineId: usersInfo[0].lineId,
        jobSystem: usersInfo[0].jobSystem,
        jobSystemId: usersInfo[0].jobSystemId,
      };
      setInfo({...info,...needsUserInfo});
      form.setFieldsValue({...info,...needsUserInfo});
      setUserModalVisible(false);
    }else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () =>{
    setUserModalVisible(false);
  }

  const renderContent = () => {
      return (
        <>
          <Row gutter={24}>
            <Col {...colStyle}>
              <FormItem name="applyName" label="申请人">
                <Input disabled />
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="applyTime" label="申请日期">
                <DatePicker disabled className='widthStyle'/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="applyDepartment" label="申请部门">
                <Input disabled />
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <Form.Item label="被审计人" name='name' rules={[{required: true, message: '被审计人不能为空'}]}>
                <Input.Group compact size="large">
                  <Input style={{ width: '80%',height: '32px', fontSize:'14px', background: '#ffffff' }} placeholder="选择被审计人" value={info ? info.name : ''} disabled={true}/>
                  <Button style={{ width: '20%' }} icon={<SearchOutlined/>} onClick={() => showSelectUserModal()} />
                </Input.Group>
              </Form.Item>
            </Col>
            <Col {...colStyle}>
              <FormItem name="orgname" label="公司名称">
                <Input disabled />
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="unitname" label="部门名称">
                <Input disabled />
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="jobname" label="岗位">
                <Input disabled />
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="jobLevel" label="职级">
                <Input disabled />
              </FormItem>
            </Col>

            <Col span={24}>
              <FormItem name="remark" labelCol={{span: 2}} label="审计事由">
                <TextArea rows={8} className='widthStyle'/>
              </FormItem>
            </Col>
            <Col span={24}>
              <Upload {...fileProps}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </Col>
          </Row>
        </>
      )
  }

  const renderFooter = () => {
      return (
        <>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      )
  };

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="离职审计填写"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>

      <SelectUserModal
        selectType={0}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />

    </Modal>
  )
};

export default connect(({user, personnel, global}) => ({
  personnel,
  global,
  currentUser: user.currentUser,
}))(CreateForm)
